<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="归属部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :disable-branch-nodes="false"
          :show-count="true"
          placeholder="请选择归属部门"
          :defaultExpandLevel="2"
          class="search-treeselect"
          style="width: 200px; margin-top: 2px"
        />
      </el-form-item> -->
      <el-form-item label="姓名" prop="personName">
        <el-input
          v-model="queryParams.personName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员类型" prop="personType">
        <el-select
          v-model="queryParams.personType"
          placeholder="请选择人员类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.base_person_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="postName">
        <!-- <el-select
          v-model="queryParams.postName"
          placeholder="请选择岗位"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.base_post_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select> -->
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入岗位"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="街道" prop="streetName">
        <el-input
          v-model="queryParams.streetName"
          placeholder="请输入街道名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="身份证号" prop="idcard">
        <el-input
          v-model="queryParams.idcard"
          placeholder="请输入身份证号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="IMEI" prop="imei">
        <el-input
          v-model="queryParams.imei"
          placeholder="请输入设备IMEI"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select
          v-model="queryParams.onlineStatus"
          placeholder="请选择在线状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.dev_online_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:person:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:person:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:person:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['base:person:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:person:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="personList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column type="index" label="序号" width="60" align="left" />
      <el-table-column
        label="所属部门单位"
        align="left"
        prop="deptName"
        minWidth="220px"
      />

      <el-table-column
        label="姓名"
        align="left"
        prop="personName"
        width="80px"
      />
      <el-table-column
        label="人员类型"
        align="left"
        prop="personType"
        width="120px"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.base_person_type"
            :value="scope.row.personType"
          />
        </template>
      </el-table-column>
      <el-table-column label="工牌" align="left" prop="deviceId" width="120">
        <template slot-scope="scope">
          <el-link
            type="primary"
            v-if="scope.row.deviceId"
            @click="routeToDevicePage(scope.row.imei)"
            >{{ scope.row.imei }}</el-link
          >
          <span v-else>未绑定</span>
        </template>
      </el-table-column>
      <el-table-column
        label="在线状态"
        align="left"
        prop="onlineStatus"
        minWidth="100px"
      >
        <template slot-scope="scope">
          <div style="display: flex; align-items: center">
            <dict-tag
              :options="dict.type.dev_online_status"
              :value="scope.row.onlineStatus"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="数据时间"
        align="left"
        prop="dataTime"
        minWidth="160px"
      />
      <el-table-column
        label="项目"
        align="left"
        prop="projectName"
        minWidth="120px"
      />
      <el-table-column
        label="街道"
        align="left"
        prop="streetName"
        minWidth="140px"
      />
      <!-- <el-table-column
        label="工号"
        align="left"
        prop="personNum"
        minWidth="160px"
      /> -->
      <el-table-column
        label="联系电话"
        align="left"
        prop="mobile"
        minWidth="140px"
      />
      <!-- <el-table-column
        label="入职日期"
        align="left"
        prop="entryDate"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.entryDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="岗位"
        align="left"
        prop="postName"
        minWidth="160px"
      />

      <!-- <el-table-column
        label="岗位"
        align="left"
        prop="postName"
        minWidth="100px"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.base_post_name"
            :value="scope.row.postName"
          />
        </template>
      </el-table-column> -->
      <el-table-column
        label="身份证号"
        align="left"
        prop="idcard"
        minWidth="180px"
      />
      <!-- <el-table-column label="性别" align="left" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="服务区域" align="left" prop="address" />
      <el-table-column
        label="紧急联系人电话"
        align="left"
        prop="emergencyPhone"
      />
      <el-table-column label="备注" align="left" prop="remark" /> -->
      <el-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="150px"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.deviceId"
            size="mini"
            type="text"
            icon="el-icon-scissors"
            @click="handleUnbind(scope.row)"
            v-hasPermi="['base:person:bind']"
            >解绑</el-button
          >
          <el-button
            v-if="!scope.row.deviceId"
            size="mini"
            type="text"
            icon="el-icon-paperclip"
            @click="handleBind(scope.row)"
            v-hasPermi="['base:person:bind']"
            >绑定</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:person:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:person:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :disable-branch-nodes="false"
                :show-count="true"
                placeholder="请选择归属部门"
                :defaultExpandLevel="2"
              />
            </el-form-item>

            <el-form-item label="人员类型" prop="personType">
              <el-select
                v-model="form.personType"
                placeholder="请选择人员类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.base_person_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="岗位" prop="postName">
              <!-- <el-select
                v-model="form.postName"
                placeholder="请选择岗位"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.base_post_name"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select> -->
              <el-input
                v-model="form.postName"
                placeholder="请输入岗位"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
              <el-input
                v-model="form.sex"
                placeholder="请输入性别"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="personName">
              <el-input
                v-model="form.personName"
                placeholder="请输入姓名"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="工号" prop="personNum">
              <el-input v-model="form.personNum" placeholder="请输入工号" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idcard">
              <el-input v-model="form.idcard" placeholder="请输入身份证号" />
            </el-form-item>
            <el-form-item label="联系电话" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>其他</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectName">
              <el-input
                v-model="form.projectName"
                placeholder="请输入项目名称"
              />
            </el-form-item>
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker
                clearable
                v-model="form.entryDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择入职日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="街道" prop="streetName">
              <el-input
                v-model="form.streetName"
                placeholder="请输入街道名称"
              />
            </el-form-item>
            <el-form-item
              label="紧急联系人电话"
              prop="emergencyPhone"
              label-width="120px"
            >
              <el-input
                v-model="form.emergencyPhone"
                placeholder="请输入紧急联系人电话"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务区域" prop="address">
          <el-input v-model="form.address" placeholder="请输入服务区域" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定 -->
    <bindDeviceDialog
      :visible.sync="bindDialogVisible"
      :deviceType="bindDeviceType"
      :personObj="personObj"
      @refreshList="getList"
    />
    <!-- 人员导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的人员数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPerson,
  getPerson,
  delPerson,
  addPerson,
  updatePerson,
  unbindDevice,
} from "@/api/base/person";

import { validateIDCard, validateMobile } from "@/utils/rulesValidate";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect } from "@/api/system/dept";

import bindDeviceDialog from "./components/bindDeviceDialog";

import { getToken } from "@/utils/auth";

export default {
  name: "Person",
  components: {
    Treeselect,
    bindDeviceDialog,
  },
  dicts: ["base_post_name", "base_person_type", "dev_online_status"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员表格数据
      personList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        personName: undefined,
        personType: undefined,
        postName: undefined,
        idcard: undefined,
        imei: undefined,
        projectName: undefined,
        streetName: undefined,
        onlineStatus: undefined,
      },
      //部门树
      deptOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
        personName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        personType: [
          { required: true, message: "人员类型不能为空", trigger: "change" },
        ],
        personNum: [
          { required: false, message: "工号不能为空", trigger: "blur" },
        ],
        mobile: [
          { required: false, message: "联系电话不能为空", trigger: "blur" },
          // {
          //   validator: validateMobile,
          //   trigger: "blur",
          // },
        ],
        entryDate: [
          { required: false, message: "入职日期不能为空", trigger: "blur" },
        ],
        postName: [
          { required: false, message: "岗位不能为空", trigger: "change" },
        ],
        idcard: [
          { required: false, message: "身份证号不能为空", trigger: "blur" },
          {
            validator: validateIDCard,
            trigger: "blur",
          },
        ],
        // sex: [{ required: false, message: "性别不能为空", trigger: "change" }],
        // address: [
        //   { required: false, message: "服务区域不能为空", trigger: "blur" },
        // ],
        // emergencyPhone: [
        //   {
        //     required: false,
        //     message: "紧急联系人电话不能为空",
        //     trigger: "blur",
        //   },
        // ],
      },
      // 人员导入参数
      upload: {
        // 是否显示弹出层（人员导入）
        open: false,
        // 弹出层标题（人员导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的人员数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/person/importData",
      },
      //绑定dialog
      bindDialogVisible: false,
      //设备类型
      bindDeviceType: "",
      personObj: null,
    };
  },
  computed: {
    deptId() {
      return this.$store.getters.choosedDeptId;
    },
  },
  watch: {
    deptId: function () {
      this.queryParams.deptId = this.deptId;
      this.getList();
    },
  },
  created() {
    this.getTreeselect();

    this.getList();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询人员列表 */
    getList() {
      this.loading = true;
      this.queryParams.deptId = this.deptId;
      listPerson(this.queryParams).then((response) => {
        this.personList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        personId: undefined,
        deptId: this.deptId,
        personName: undefined,
        personType: undefined,
        deviceId: undefined,
        personNum: undefined,
        mobile: undefined,
        entryDate: undefined,
        postName: undefined,
        idcard: undefined,
        sex: undefined,
        address: undefined,
        emergencyPhone: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        streetName: undefined,
        projectName: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.personId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const personId = row.personId || this.ids;
      getPerson(personId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改人员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.personId != null) {
            updatePerson(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addPerson(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const personIds = row.personId || this.ids;
      this.$modal
        .confirm('是否确认删除"' + (row.orderName || "已勾选") + '"的数据项?')
        .then(() => {
          this.loading = true;
          return delPerson(personIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "base/person/export",
        {
          ...this.queryParams,
        },
        `人员_${new Date().getTime()}.xlsx`
      );
    },
    handleBind(row) {
      this.personObj = row;
      this.bindDeviceType = "work_card";
      this.bindDialogVisible = true;
    },
    /** 解绑 */
    handleUnbind(row) {
      this.$confirm('是否确认解绑"' + row.personName + '"上的设备?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return unbindDevice({
            deviceId: row.deviceId,
            personId: row.personId,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("解绑成功");
        })
        .catch(function () {});
    },
    routeToDevicePage(imei) {
      this.$router.push({
        // path: "/device",
        name: "Device",
        params: {
          imei: imei,
        },
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "人员导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "base/person/importTemplate",
        {},
        `person_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
